const express = require("express");
const router = express.Router();
const { default: mongoose } = require("mongoose");

// 获取 schema
const { Schema } = mongoose;
const url = "mongodb://127.0.0.1:27017/shopApp";
mongoose.connect(url)
    .then(() => console.log("链接成功数据库"))
    .catch(err => console.error("连接数据库失败:", err));

// 创建数据模板
const dataListSchema = new Schema({
    username: { type: String },
    pic: { type: String },
    color: { type: String },
    size: { type: String },
    count: { type: Number },
    price: { type: Number },
    id: { type: Number },
    itemPrice: { type: Number },
    visible: { type: Boolean },
    checked: { type: Boolean }
});

const AddDataModel = mongoose.model("getDetail", dataListSchema);


// 添加
router.post("/add", async (req, res, next) => {
    try {
        const { username, pic, color, size, count, price, id, itemPrice, checked, visible } = req.body;
        // 验证输入数据
        if (!(!username || !pic || !color || !size || !count || !price || !id || !itemPrice || !checked || !visible)) {
            return res.status(400).json({ msg: "所有字段都是必填项", code: 400 });
        }
        const newData = await AddDataModel.create({
            username,
            pic,
            color,
            size,
            count,
            price,
            id,
            itemPrice,
            visible,
            checked
        });

        res.status(201).json({ msg: "请求成功", code: 201, data: newData });
    } catch (error) {
        console.error("添加数据时出错:", error);
        res.status(500).json({ msg: "服务器内部错误", code: 500 });
    }
    next()
});

module.exports = router;


